package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

// main
//
//	@Description: response
func main() {

	http.HandleFunc("/res/string", handleRespSting)
	http.HandleFunc("/res/html", handleRespHtml)
	http.HandleFunc("/res/json", handleRespJson)
	http.HandleFunc("/res/redirect", handleRespRedirect)

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("ListenAndServe: ", err)
		return
	}
}

// handleGetParam
//
//	@Description: 返回字符串
//	@param w
//	@param r
func handleRespSting(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello world"))
}

// handleRespHtml
//
//	@Description: 返回html
//	@param w
//	@param r
func handleRespHtml(w http.ResponseWriter, r *http.Request) {
	html := `<html>
 <head>
 <title>测试响应内容为网页</title>
 <meta charset="utf-8"/>
 </head>
 <body>
 我是以网页的形式响应过来的！
 </body>
</html>`
	w.Write([]byte(html))
}

// handleRespJson
//
//	@Description: 返回json
//	@param w
//	@param r
func handleRespJson(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var resMap = map[string]interface{}{
		"name": "张三",
		"age":  18,
		"sex":  "男",
	}
	marshal, _ := json.Marshal(resMap)
	w.Write(marshal)
}

// handleRespRedirect
//
//	@Description: 重定向
//	@param w
//	@param r
func handleRespRedirect(w http.ResponseWriter, r *http.Request) {
	//以下操作必须要在 WriteHeader 之前进行
	w.Header().Set("Location", "https:www.baidu.com")
	w.WriteHeader(302)
}
